package handlers

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// UserInfo 用户信息结构
type UserInfo struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Phone    string `json:"phone"`
}

// LoginRequest 登录请求结构
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// LoginResponse 登录响应结构
type LoginResponse struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
	UserInfo  UserInfo  `json:"user_info"`
}

// Login 登录处理器
func Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Printf("[DEBUG] Login binding error: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	fmt.Printf("[DEBUG] Login request: username=%s, password=%s\n", req.Username, req.Password)

	// 模拟用户验证
	if req.Username == "admin" && req.Password == "password" {
		response := LoginResponse{
			Token:     "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
			ExpiresAt: time.Now().Add(24 * time.Hour),
			UserInfo: UserInfo{
				ID:       1,
				Username: "admin",
				Email:    "admin@example.com",
				Phone:    "13800138000",
			},
		}
		c.JSON(http.StatusOK, gin.H{
			"success": true,
			"message": "Login successful",
			"data":    response,
		})
	} else {
		c.JSON(http.StatusUnauthorized, gin.H{
			"success": false,
			"message": "Invalid credentials",
		})
	}
}

// GetUserInfo 获取用户信息处理器
func GetUserInfo(c *gin.Context) {
	userInfo := UserInfo{
		ID:       1,
		Username: "admin",
		Email:    "admin@example.com",
		Phone:    "13800138000",
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "User info retrieved successfully",
		"data":    userInfo,
	})
}

// UpdateUserInfo 更新用户信息处理器
func UpdateUserInfo(c *gin.Context) {
	var userInfo UserInfo
	if err := c.ShouldBindJSON(&userInfo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 模拟更新用户信息
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "User info updated successfully",
		"data":    userInfo,
	})
}

// Ping 健康检查处理器
func Ping(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "pong",
		"time":    time.Now().Format(time.RFC3339),
	})
}
